package mspbots.data.tl.prod.jira.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultMessageModel;
import mspbots.data.tl.prod.jira.mapper.JiraUserMapper;
import mspbots.data.tl.prod.jira.model.JiraUser;
import mspbots.data.tl.prod.jira.service.JiraUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

/**
 * @author Jay.Yang
 */

@Service
@Log4j2
@DS("master")
public class JiraUserServiceImpl extends AbstractBaseServiceImpl<JiraUserMapper, JiraUser>
        implements JiraUserService {

    @Override
    public void sync(ResultMessageModel model) {
        if (ObjectUtils.isEmpty(model.getEntity()) || !ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            log.error("jira.user.tl entry is null,or Action No Add");
            return;
        }
        JsonNode node = model.getEntity();
        JiraUser data = JiraUser.builder()
                .key(node.get("key").asText())
                .name(node.get("name").asText())
                .displayName(node.get("displayName").asText())
                .emailAddress(node.get("emailAddress").asText())
                .active(node.get("active").asBoolean())
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(model.getTenantId());
        JiraUser dbData = super.baseMapper.selectOne(Wrappers.<JiraUser>lambdaQuery()
                .eq(JiraUser::getTenantCode, data.getTenantCode())
                .eq(JiraUser::getKey, data.getKey())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }
}
